<?php

namespace mz\models;

use Yii;
use yii\web\UploadedFile;

class UploadFile
{
    /**
     * 临时文件转永久
     * @param string $filename upfile
     * @param $type
     * @param $action
     * @return array|string
     */
    public static function uploadFiles($filename,$type,$action)
    {
        $uploadFileInstance = UploadedFile::getInstanceByName($filename);

        if ($uploadFileInstance === null || $uploadFileInstance->hasError) {
            return "文件不存在";
        }

        $ymd = date('ymd');

        #存储到本地的路径
        $savePath = Yii::getAlias('@data').'/'.$action.'/'.$ymd.'/';
        # 判断目录是否存在，不存在则创建
        if(!is_dir($savePath)){
            mkdir($savePath , 0777 , true);
        }

        # 存储数据库的地址
        $saveUrl = $action.'/'.$ymd.'/';

        $allowType = ['gif', 'jpg', 'jpeg', 'png', 'bmp'];
        $allowSize = 3145728;
        $baseName = $uploadFileInstance->getBaseName();

        # 图片格式
        $file_ext = $uploadFileInstance->getExtension();
        if (empty($file_ext) || $type != 'image' || !in_array($file_ext, $allowType)) {
            return '只允许上传以下格式的图片: '.implode(', ', $allowType);
        }

        # 大小判断
        $fileSize = $uploadFileInstance->size;
        if ($fileSize > $allowSize) {
            return '图片不能大于'.$allowSize;
        }

        #图片名称
        $new_file_name=date("YmdHis").'_'.rand(10000,99999).'.'.$file_ext;
        $uploadFileInstance->saveAs($savePath.$new_file_name);

        # 缩略图 width 50px  height 35px
        $thumb50Path = ImageModel::thumbnail($savePath.$new_file_name,50,35);

        # 300px * 150px
        $thumb300Path = ImageModel::thumbnail($savePath.$new_file_name,300,150);

        return ['path'=>$savePath,'url'=>$saveUrl,'name'=>$baseName,'thumb_name' => $thumb300Path,'source_name'=>$new_file_name,'ext'=>$file_ext];
    }
}
